import json
from fastapi import Depends
from sqlalchemy.orm import Session, session
from Model.community.common_text import Commontext
from Model.community.community import user_to_community_expand
from Model.community.response.commontext import CommText_search_preinfo
from Model.default import get_db
from config.comunity import SEARCH_ARTICLE_LENGTH
def string_to_list(s: str) -> list:
    """
    将字符串逐字符拆分为列表，保持顺序且不去重
    :param s: 输入的字符串
    :return: 字符列表
    """
    return list(s)
def get_commonText_Search_By_keywords(keywords:str,userid:int=0,limit:int=1):
    """
    处理文章搜索
    :param userid:
    :param keywords:
    :param db:
    :return:
    """
    db=get_db()
    try:
        DATA = []
        if userid:
            userdata = db.query(user_to_community_expand).filter_by(user_id=userid).first()
            if userdata:
                predata = json.loads(userdata.search_history or json.dumps([]))
                predata.append(keywords)
                # 使用集合去重一下
                predata = list(set(list(predata)))
                userdata.search_history = json.dumps(predata)
                db.commit()
        # 处理含有文段
        pre_data = (db.query(Commontext).filter(Commontext.title.like('%' + keywords + '%'))
                    .offset((limit-1)*SEARCH_ARTICLE_LENGTH)
                    .limit(SEARCH_ARTICLE_LENGTH).all())
        for i in pre_data:
            middledata=i.to_dict()
            middledata['title']=string_to_list(i.title)
            DATA.append(CommText_search_preinfo(**middledata).model_dump(by_alias=True))

        return DATA
    except Exception as e:
        print(e)
    finally:
        db.close()
